package net.pm.core.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.pm.common.toolkit.DevConstant;
import net.pm.common.toolkit.date.DateUtils;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component("SpringMVCInterceptor")
public class SpringMVCInterceptor extends HandlerInterceptorAdapter {

		/*//不记录足迹的url
		private static final String[] unfootprint_urls = 
			{"/addr/province.htm","/addr/city.htm","/addr/district.htm"};*/
		
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		BaseController baseController = (BaseController) handler;
		
		baseController.setRequest(request);
		baseController.setSession(request.getSession(true));
		
		/*request.getMethod();
		//请求的url
		//RequestMapping requestMapping = baseController.getClass().getAnnotation(RequestMapping.class);
		//if(requestMapping != null){
			//String classRequestMappingVal = requestMapping.value()[0];
			//String urlPrefix = PMConstant.PROJECT_NAME.concat(classRequestMappingVal);
			final String requesturi = request.getRequestURI().replaceAll("/".concat(PMConstant.PROJECT_NAME), "");
			//System.out.println(requesturi);
			if(!ArrayUtils.contains(unfootprint_urls, requesturi))
				baseController.putFootPrint(requesturi);
		//}
*/		
		
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		if (modelAndView != null) {
			String viewName = modelAndView.getViewName();
			BaseController baseController = (BaseController) handler;
			if (viewName != null && (!viewName.startsWith("redirect:"))) {
				// 提示信息
				modelAndView.addObject(DevConstant.SHOW_MESSAGESS,
						baseController.obtainSessionMessage());
				// 网站根路径
				modelAndView.addObject("basepath", DevConstant.BASEPATH);
				// 当前时间
				modelAndView.addObject(DevConstant.SESSION_CURRENT_TIME,
						DateUtils.obtainCurrentDate());
				
				modelAndView.addObject("pageno", DevConstant.PAGE_DEFAULT_NO);
				modelAndView
						.addObject("pagesize", DevConstant.PAGE_DEFAULT_SIZE);
			}
		}
		
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

}
